package com.stox.client.ui.javafx.chartingy.model.node;

import javafx.scene.shape.Line;

import com.stox.client.ui.javafx.chartingy.model.Rectangle;
import com.stox.client.ui.javafx.chartingy.model.axis.DateAxis;
import com.stox.client.ui.javafx.chartingy.model.plot.Data;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;
import com.stox.shared.model.Bar;
import com.stox.shared.model.Scrip;

public class PriceLineDataNode extends AbstractPriceNode {
	
	private Line line = new Line();
	
	public PriceLineDataNode(Data<Scrip, Bar> data) {
		super(data);
		getChildren().addAll(line);
		UI.style(this, CSS.barNode);
		UI.style(line, CSS.priceLineDataNode);
	}
	
	@Override
	public void updateColor() {
		super.updateColor();
		Data<Scrip,Bar> data = getData();
		int size = data.getPlot().getData().size();
		if(data.getIndex() < size - 1){
			setStyle("-fx-bar-color:"+UI.web(getColor())+";");
		}else{
			line.setVisible(false);
		}
	}
	
	@Override
	public void layoutChartChildren() {
		if(!line.isVisible()) return;
		
		Data<Scrip,Bar> data = getData();
		Bar bar = (Bar)data.getExtraValue();
		Bar previousBar = null;
		int size = data.getPlot().getData().size();
		if(data.getIndex() < size - 1){
			previousBar = data.getPlot().getData().get(data.getIndex() + 1).getExtraValue();
		}else{
			return;
		}
		
		DateAxis dateAxis = data.primaryChart().getDateAxis();
		double x = dateAxis.getDisplayPosition(data.getIndex());
		double width = dateAxis.getUnitWidth();
		double high = getDisplayPosition(bar.getHigh());
		double low = getDisplayPosition(bar.getLow());
		
		Rectangle rectangle = getRectangle();
		rectangle.setX(x - width/2);
		rectangle.setWidth(width);
		rectangle.setY(high);
		rectangle.setHeight(low - high);
		
		line.setStartX(x - width);
		line.setStartY(getDisplayPosition(previousBar.getClose()));
		line.setEndX(x);
		line.setEndY(getDisplayPosition(bar.getClose()));
	}
}
